package com.wenlong.train_ticketing_system_springboot.querymodule.config;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 苏文龙
 * @version 1.0
 */
@Configuration
public class RabbitConfig {
    public static final String DELAY_MSG_QUEUE = "delay_msg_queue";
    public static final String DELAY_MSG_DELETE_QUEUE = "delay_msg_delete_queue";

    public static final String DELAY_MSG_EXCHANGE = "delay_msg_exchange";
    public static final String DELAY_MSG_DELETE_EXCHANGE = "delay_msg_delete_exchange";

    public static final String DELAY_MSG_ROUTING_KEY = "delay_msg_routing_key";
    public static final String DELAY_MSG_DELETE_ROUTING_KEY = "delay_msg_delete_routing_key";

    /**
     * @return 定义延迟队列
     */
    @Bean(name = "msgQueue")
    public Queue msgQueue(){
        return new Queue(DELAY_MSG_QUEUE);
    }
    // 删除 queue
    @Bean(name = "msgDeleteQueue")
    public Queue msgDeleteQueue(){
        return new Queue(DELAY_MSG_DELETE_QUEUE);
    }

    /**
     * @return 延时队列交换机, 交换机类型：CustomExchange
     */
    @Bean(name = "customExchange")
    public CustomExchange customExchange(){
        Map<String, Object> args = new HashMap<>();
        args.put("x-delayed-type", "direct");
        return new CustomExchange(DELAY_MSG_EXCHANGE, "x-delayed-message", true, false, args);
    }
    @Bean(name = "customDeleteExchange")
    public CustomExchange customDeleteExchange(){
        Map<String, Object> args = new HashMap<>();
        args.put("x-delayed-type", "direct");
        return new CustomExchange(DELAY_MSG_DELETE_EXCHANGE, "x-delayed-message", true, false, args);
    }

    /**
     * 为延迟队列绑定交换机
     * @param msgQueue 延迟队列
     * @param customExchange 直接交换机
     * @return Binding关系
     */
    @Bean
    public Binding QueueBingToExchange(@Qualifier("msgQueue") Queue msgQueue,
                                       @Qualifier("customExchange") CustomExchange customExchange){
        return BindingBuilder.bind(msgQueue).to(customExchange).with(DELAY_MSG_ROUTING_KEY).noargs();
    }
    // 删除binding
    @Bean
    public Binding DelQueueBingToExchange(@Qualifier("msgDeleteQueue") Queue msgDeleteQueue,
                                       @Qualifier("customDeleteExchange") CustomExchange customDeleteExchange){
        return BindingBuilder.bind(msgDeleteQueue).to(customDeleteExchange).with(DELAY_MSG_DELETE_ROUTING_KEY).noargs();
    }

    /*    @Bean
    public Binding msgBinding(){
        return BindingBuilder.bind(msgQueue()).to(directExchange()).with(MSG_ROUTING_KEY);
    }*/
}
